import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { RedisClientType } from 'redis';

@Injectable()
export class RedisService {
  @Inject('REDIS_SERVICE')
  private redisClient: RedisClientType;

  async set(key: string, value: string, tll?: number) {
    try {
      await this.redisClient.set(key, value);
      if (tll) {
        await this.redisClient.expire(key, tll);
      }
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async get(key: string) {
    try {
      return await this.redisClient.get(key);
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async del(key: string) {
    try {
      return await this.redisClient.del(key);
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async hashSet(
    key: string,
    obj: { readNum?: number; support?: number; star?: number },
    ttl?: number,
  ) {
    try {
      for (const name in obj) {
        await this.redisClient.hSet(key, name, obj[name]);
      }
      if (ttl) {
        await this.redisClient.expire(key, ttl);
      }
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async hashGet(key: string) {
    try {
      return await this.redisClient.hGetAll(key);
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async getKeys(pa: string) {
    try {
      return await this.redisClient.keys(pa);
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
